﻿using System.Collections.Generic;
using System.Linq;

namespace PdfGeneratorNetFree
{
	using System;
	using System.IO;
	using System.Runtime.Serialization.Formatters.Binary;
	using PdfContentItem;

	[Serializable]
	public class PdfContent : ICloneable
	{
		public readonly string Name;
		public readonly float OffsetX;
		public readonly float OffsetY;

		public readonly Dictionary<string, AbstractPdfContentItem> ItemDic;

		public AbstractPdfContentItem[] Items { get { return this.ItemDic.Values.ToArray(); } }

		public PdfContent(string name, Dictionary<string, AbstractPdfContentItem> items, string offsetX, string offsetY)
		{
			this.Name = name;
			this.ItemDic = items;
			this.OffsetX = string.IsNullOrEmpty(offsetX) ? 0 : float.Parse(offsetX);
			this.OffsetY = string.IsNullOrEmpty(offsetY) ? 0 : float.Parse(offsetY);
		}

		public void Clear()
		{
			//for (int i = 0; i < this.PdfContentItems.Length; i++)
			//{
			//    this.PdfContentItems[i] = null;
			//}

			//this.PdfContentItems = null;
		}

		/// <summary>
		/// Deep Copy
		/// </summary>
		/// <returns>Copy Object</returns>
		public PdfContent Clone()
		{
			var binaryFormatter = new BinaryFormatter();
			using (var stream = new MemoryStream())
			{
				binaryFormatter.Serialize(stream, this);
				stream.Position = 0;
				return (PdfContent)binaryFormatter.Deserialize(stream);
			}
		}

		/// <summary>
		///  ICloneable.Cloneの明示的な実装【ICloneable型から呼ばれた時だけ実行される。Cloneメッソッド実行後のキャストを避けるための実装】
		/// </summary>
		/// <returns>Copy Object</returns>
		object ICloneable.Clone()
		{
			return this.Clone();
		}

		/// <summary>
		/// 添字でのアクセス可能にするインデクサーの定義
		/// </summary>
		/// <returns></returns>
		public AbstractPdfContentItem this[string s]
		{
			get
			{
				if (!this.ItemDic.ContainsKey(s))
				{
					throw new InvalidOperationException("key not Found. key=" + s);
				}

				return this.ItemDic[s];
			}
		}

	} // Class
}
